package org.wlw.teacher.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class DBUtils {
    private static SqlSessionFactory sqlSessionFactory;

    //单例模式
    private static SqlSessionFactory createSqlSessionFactory() {
        if(sqlSessionFactory!=null) return sqlSessionFactory;
        try {
            String xml = "mybatis-config.xml";
            //可以找到xml 的路径
            InputStream xmlPath = Resources.getResourceAsStream(xml);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(xmlPath);
            return sqlSessionFactory;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SqlSession openSession() {
        return createSqlSessionFactory().openSession();
    }

    public static void close(SqlSession sqlSession) {
        if(sqlSession!=null) sqlSession.close();
    }
}
